package com.demo.xmtx.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;

public class InventoryManagementSystem {
  private final Lock lock = new ReentrantLock();

  // 可定时的锁
  public void updateInventoryWithTimeout() {
    boolean lockAcquired = false;
    try {
      // 尝试在3秒内获取锁
      lockAcquired = lock.tryLock(3, TimeUnit.SECONDS);
      if (lockAcquired) {
        // 执行库存更新操作
        System.out.println("Inventory updated by " + Thread.currentThread().getName());
      } else {
        // 超时未获取到锁，执行其他逻辑
        System.out.println("Failed to acquire lock, performing other tasks by " + Thread.currentThread().getName());
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      if (lockAcquired) {
        lock.unlock();
      }
    }
  }

  // 可中断的锁
  public void updateInventoryWithInterrupt() {
    try {
      // 尝试获取锁，可响应中断
      lock.lockInterruptibly();
      try {
        // 执行库存更新操作
        System.out.println("Inventory updated by " + Thread.currentThread().getName());
      } finally {
        lock.unlock();
      }
    } catch (InterruptedException e) {
      // 响应中断
      System.out.println("Thread interrupted while waiting for lock by " + Thread.currentThread().getName());
    }
  }

  public static void main(String[] args) {
    InventoryManagementSystem system = new InventoryManagementSystem();

    // 创建多个线程测试可定时的锁
    for (int i = 0; i < 50; i++) {
      new Thread(system::updateInventoryWithTimeout).start();
    }

    // 创建多个线程测试可中断的锁
    for (int i = 0; i < 50; i++) {
      Thread thread = new Thread(system::updateInventoryWithInterrupt);
      thread.start();
      // 模拟中断
      if (i == 2) {
        thread.interrupt();
      }
    }
  }
}